package com.example.icongyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.icongyou.R;
import com.example.icongyou.adapter.ChapterAdapter;
import com.example.icongyou.api.ChapterApi;
import com.example.icongyou.api.CourseApi;
import com.example.icongyou.bean.Chapter;
import com.example.icongyou.bean.Course;
import com.example.icongyou.bean.StudentCourseProgress;
import com.example.icongyou.retrofit.RetrofitClient;
import com.example.icongyou.util.UserUtils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CourseDetailActivity extends AppCompatActivity {

    // 控件声明
    private TextView tvCourseName;       // 课程名称
    private TextView tvTeacherName;     // 教师名称
    private TextView tvCourseDesc;      // 课程描述
    private RecyclerView rvChapters;    // 章节列表

    // 数据变量
    private String courseId;            // 课程ID
    private Course course;              // 课程完整信息
    private List<Chapter> chapterList;  // 章节数据集合

    private String currentStudentId; // 从登录信息获取

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail); // 确保布局正确

        // 获取课程ID（从跳转意图中获取）
        courseId = getIntent().getStringExtra("courseId");
        String currentStudentId = UserUtils.getCurrentStudentId(this); // 替换为实际获取方式

        loadCourseDetail(); // 加载课程详情
        loadCourseProgress(); // 加载进度
        loadChapters(); // 加载章节列表
    }

    // 新增：加载并展示课程进度
    private void loadCourseProgress() {
        CourseApi api = RetrofitClient.getInstance().create(CourseApi.class);
        String currentStudentId = UserUtils.getCurrentStudentId(this);
        api.getCourseProgress(courseId, currentStudentId)
                .enqueue(new Callback<StudentCourseProgress>() {
                    @Override
                    public void onResponse(Call<StudentCourseProgress> call, Response<StudentCourseProgress> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            StudentCourseProgress progress = response.body();
                            // 更新进度条（布局中需添加ProgressBar和TextView）
                            ProgressBar progressBar = findViewById(R.id.pb_course_progress);
                            TextView progressText = findViewById(R.id.tv_progress);
                            // 假设进度是0-100的数值，直接设置
                            progressBar.setProgress((int) progress.getProgressRate());
                            progressText.setText(progress.getProgressRate() + "%");
                        }
                    }

                    @Override
                    public void onFailure(Call<StudentCourseProgress> call, Throwable t) {
                        Toast.makeText(CourseDetailActivity.this, "进度获取失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        tvCourseName = findViewById(R.id.tv_detail_course_name);
        tvTeacherName = findViewById(R.id.tv_detail_teacher);
        tvCourseDesc = findViewById(R.id.tv_detail_description);
        rvChapters = findViewById(R.id.rv_chapters);
        rvChapters.setLayoutManager(new LinearLayoutManager(this));
        tvCourseName = findViewById(R.id.tv_detail_course_name);
        tvTeacherName = findViewById(R.id.tv_detail_teacher);
        tvCourseDesc = findViewById(R.id.tv_detail_description);
        rvChapters = findViewById(R.id.rv_chapters);
        rvChapters.setLayoutManager(new LinearLayoutManager(this));

        // 新增按钮初始化和点击事件
        Button btnTaskDashboard = findViewById(R.id.btn_task_dashboard);
        btnTaskDashboard.setOnClickListener(v -> {
            // 跳转到任务数据看板页面
            Intent intent = TaskDashboardActivity.newIntent(
                    CourseDetailActivity.this,
                    courseId  // 传递当前课程ID
            );
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });
    }

    /**
     * 直接绑定传递的课程数据
     */
    private void bindCourseData() {
        tvCourseName.setText(course.getCourseName());
        tvTeacherName.setText("授课教师：" + course.getTeacherName());
        tvCourseDesc.setText(course.getDescription() != null ? course.getDescription() : "暂无课程描述");
    }

    /**
     * 从网络加载课程详情
     */
    private void loadCourseDetail() {
        RetrofitClient.getCourseApi().getCourseById(courseId).enqueue(new Callback<Course>() {
            @Override
            public void onResponse(@NonNull Call<Course> call, @NonNull Response<Course> response) {
                if (response.isSuccessful() && response.body() != null) {
                    course = response.body();
                    bindCourseData();
                } else {
                    Toast.makeText(CourseDetailActivity.this, "获取课程详情失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<Course> call, @NonNull Throwable t) {
                Toast.makeText(CourseDetailActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 加载章节列表
     */
    private void loadChapters() {
        ChapterApi chapterApi = RetrofitClient.getChapterApi();
        chapterApi.getChaptersByCourseId(courseId).enqueue(new Callback<List<Chapter>>() {
            @Override
            public void onResponse(@NonNull Call<List<Chapter>> call, @NonNull Response<List<Chapter>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    chapterList = response.body();
                    setupChapterAdapter();
                } else {
                    Toast.makeText(CourseDetailActivity.this, "获取章节列表失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Chapter>> call, @NonNull Throwable t) {
                Toast.makeText(CourseDetailActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 初始化章节适配器
     */
    private void setupChapterAdapter() {
        // 章节适配器
        ChapterAdapter chapterAdapter = new ChapterAdapter(this, chapterList);
        rvChapters.setAdapter(chapterAdapter);
    }

    /**
     * 外部跳转方法
     */
    public static void start(android.app.Activity activity, Course course) {
        Intent intent = new Intent(activity, CourseDetailActivity.class);
        intent.putExtra("course", course);
        activity.startActivity(intent);
        // 修正方法名拼写
        activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }
}